package com.tl.boot.main.aspect;

import com.tl.boot.common.annotation.ChooseDataSource;
import com.tl.boot.common.enums.LocalDataBaseEnum;
import com.tl.boot.common.utils.LogUtil;
import com.tl.boot.main.datasource.DataSourceType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * com.tl.boot.main.aspect -- DatasourceAspect
 * Description:
 * Created by joshua_liu <a href="mailto:joshualwork@163.com"></a>
 * On 2019/9/25 10:10
 */
@Aspect
@Component
@Order(-98)
public class DatasourceAspect {
    @Pointcut("@annotation(com.tl.boot.common.annotation.ChooseDataSource)||@within(com.tl.boot.common.annotation.ChooseDataSource)")
    public void pointCut() {

    }
    @Before("pointCut()")//拦截我们的注解
    public void changeDataSource(JoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        ChooseDataSource chooseDataSource = method.getAnnotation(ChooseDataSource.class);
        LocalDataBaseEnum localDataBaseEnum = chooseDataSource.value();
        LogUtil.debug(String.format("数据源类型为：%s",localDataBaseEnum.toString()));
        DataSourceType.setDataBaseType(localDataBaseEnum);
    }

    @After("@annotation(chooseDataSource)||@within(chooseDataSource)") //清除数据源的配置
    public void restoreDataSource(ChooseDataSource chooseDataSource) {
        LogUtil.debug("清除数据源信息了");
        DataSourceType.clearDataBaseType();
    }

}
